package com.eu.ebpm.engine.cmd.pvm;

import java.util.Date;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.eu.ebpm.SpringContext;
import com.eu.ebpm.engine.entity.deploy.Mission;
import com.eu.ebpm.engine.entity.deploy.Transfer;
import com.eu.ebpm.engine.entity.history.HisTask;
import com.eu.ebpm.engine.entity.runtime.TaskEntity;
import com.eu.ebpm.engine.exception.WorkFlowException;
import com.eu.ebpm.engine.pvm.PvmEngine;
import com.eu.ebpm.engine.repository.HisTaskRepository;
import com.eu.ebpm.engine.task.DelegateTask;
import com.eu.ebpm.engine.task.ServiceTaskExecute;

/**
 * 
 * @author 王晓华
 * @since 2015-1-24 下午10:34:50
 * @version v1.0
 */
@Component
public class ServiceTaskIntoCommand extends PvmCommand {

	@Autowired
	private HisTaskRepository hisTaskRepository;
	
	public Map<String, Object> execute(Mission m, TaskEntity task, Map<String, Object> previousVariables) {

		// 1、获取 ServiceTaskExecute
		ServiceTaskExecute serviceTaskExecute = null;
		try {
			serviceTaskExecute = SpringContext.getBean(m.getServiceTaskExecute());
		} catch (Exception e) {
			throw new WorkFlowException(String.format("ServiceTask获取不到执行beanService, missionName = %s, missionDesc=%s, beanName = %s", m.getName(), m.getDesc(), m.getServiceTaskExecute()));
		}

		// 2、执行自动任务，获取返回参数
		DelegateTask delegateTask = new DelegateTask(task, previousVariables);
		serviceTaskExecute.execute(delegateTask);
		Map<String, Object> vs = delegateTask.getVariables();

		// 3、记录serviceTask的执行记录；variables的执行记录
		Transfer nextTransfer = PvmEngine.matchedNextTransfer(m.getTransfers(), vs);
		HisTask hisTask = new HisTask(m.getType(), m.getName(), m.getDesc(), nextTransfer.getName(), task.getExecutionId(), task.getRootExecutionId(), m.getId(), null, null, new Date(), new Date());
		hisTask.setTransferDesc(nextTransfer.getDesc());
		hisTaskRepository.insert(hisTask);

		// 4、插入参数
		super.insertHisTaskVariable(hisTask.getId(), vs);

		return vs;
	}

}
